import { api } from "boot/axios";
import { useAPIStore } from "src/stores/api";
import { useUiStore } from "stores/ui";
import { Notify } from "quasar";
const ui = useUiStore();

/**
 * 接口数据格式与本地不一致，进行转换
 * @param {*} language
 * @returns
 */
function formatLanguage(language) {
  let formatLanguage = "";
  switch (language) {
    case "zh-CN":
      formatLanguage = "zh_CN";
      break;
    case "en-US":
      formatLanguage = "en_US";
      break;
    case "zh_CN":
      formatLanguage = "zh-CN";
      break;
    case "en_US":
      formatLanguage = "en-US";
      break;
  }
  return formatLanguage;
}

/**
 * 切换语言
 * @param {*} language
 */
export const switchLanguage = function (language) {
  api
    .get(useAPIStore().centerUrl + "contend/set/language", {
      params: {
        language: formatLanguage(language),
      },
    })
    .then((res) => {
      Notify.create({
        message: "语言切换成功",
      });
      ui.changeLanguage(language);
      location.reload();
    })
    .catch((e) => {
      Notify.create({
        message: "语言切换失败",
        type: "negative",
      });
    });
};

/**
 * 设置语言
 */
export const setLanguage = function () {
  api
    .get(useAPIStore().centerUrl + "contend/get/language")
    .then((res) => {
      console.log("语言", res);
      if (res.data.code === 200) {
        const language = res.data.data[0].value;
        const serveLanguage = formatLanguage(language);
        console.log("获取到语言", language, serveLanguage);
        if (ui.language !== serveLanguage) {
          ui.changeLanguage(formatLanguage(language));
          location.reload();
        }
      }
    })
    .catch((e) => {
      // console.log('获取语言失败', e)
    });
};
